"""模拟服务器发送数据，做测试使用"""
import socket
import os
import time

HOST, PORT = "10.251.135.7", 50003
f = open(r'../bit_file/minisys_test.bit', mode='rb')
size = os.path.getsize(r'../bit_file/minisys_test.bit')

program = bytearray(b'\xA1\x3A\x00\x10M0\x00\x00\x00\x00\x00\x00\x00\x00')
program[6:10] = size.to_bytes(4, 'big')
data = f.read(size)
display = b'\x17\x20\x00\x00\x00\x00'
# 按下keyboard(1,1)
keyboard11_on = b'\x17\x40\xb0\x00\x00\x00'
# 松开keyboard(1,1)
keyboard11_off = b'\x17\x40\x30\x00\x00\x00'
# 放开button[0]
button0_off = b'\x17\x40\x20\x00\x00\x00'
# 按下button[0]
button0_on = b'\x17\x40\xa0\x00\x00\x00'
close = b'\x17\x08\x00\x00\x00\x00'
# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(program)  # 烧录
    sock.sendall(data)
    print(len(data))
    sock.sendall(display)  # 执行serial.recv()
    time.sleep(1)
    for i in range(30):
        sock.sendall(keyboard11_on)  # 按下keyboard(1,1)
        sock.sendall(keyboard11_off)
        sock.sendall(keyboard11_off)  # 关闭keyboard(1,1)
        sock.sendall(keyboard11_on)
    sock.sendall(keyboard11_off)
    sock.sendall(button0_off)
    sock.sendall(button0_on)
    sock.sendall(button0_off)
    # Receive data from the server and shut down
    t1 = time.time()
    for i in range(20):
        received = sock.recv(11+6)
        print(received.hex(' '))
    t2 = time.time()
    print(t2 - t1)
    sock.sendall(close)
